<?php
class Core_Model_DbTable_Comments extends Core_Model_DbTable_Base_Action {
    protected $_name = "comments";
    protected $_id_social_name = 'id_social_comment';
    
    public function getDetail($id_socials) {
        $facebook_wraper = new MKT_Facebook_Wraper();
        $params = 'fields=message,from';
        $fb_comment_details = $facebook_wraper->getBatchData($id_socials, $params);
        
        $buffer_comment_db = new Core_Model_DbTable_BufferComments();
        $db_comment_details = $buffer_comment_db->getCommentDetail($id_socials);
        
        $id_social_posts = array();
        
        for ($i = 0; $i < sizeof($db_comment_details); $i++) {
            $id_social_comment = $db_comment_details[$i]['id_social_comment'];
            $id_social_post    = $db_comment_details[$i]['id_social_post'];
                        
            $message   = $fb_comment_details[$id_social_comment]['message'];
            $from_name = $fb_comment_details[$id_social_comment]['from']['name'];
            
            $db_comment_details[$i]['message']        = $message;
            $db_comment_details[$i]['from_name']      = $from_name;
            
            $id_social_posts[] = $id_social_post;
        }
        
        $user_db = new Core_Model_DbTable_Users();
        $latest_access_token = $user_db->getLatestAccessToken();
        $params = "access_token=$latest_access_token";
        $post_messages = $facebook_wraper->getBatchData($id_social_posts, $params);
        
        for ($i = 0; $i < sizeof($db_comment_details); $i++) {
            $id_social_post = $db_comment_details[$i]['id_social_post'];
            $fb_post_data   = $post_messages[$id_social_post];
            
            $target_message = NULL;
            if (isset($fb_post_data['message'])) {
                $target_message = $fb_post_data['message'];
            } elseif (isset($fb_post_data['name'])) {
                $target_message = $fb_post_data['name'];
            }
            $picture = $fb_post_data['picture'];

            $db_comment_details[$i]['target_message'] = $target_message;
            $db_comment_details[$i]['picture'] = $picture;
            
            if (isset($fb_post_data['from'])) {
                $db_comment_details[$i]['target_id_social_from'] = $fb_post_data['from']['id'];
            } else {
                $db_comment_details[$i]['target_id_social_from'] = $db_comment_details[$i]['id_social_user'];
            }
            
            $db_comment_details[$i]['target_created_time'] = strtotime($fb_post_data['updated_time']);
        }

        return $db_comment_details;
    }
    
    protected function getCols() {
        return array (
            'id_social_page', 'id_social_user', 'id_social_post',
            'id_social_comment', 'message', 'created_time'
        );
    }
}
?>
